package com.rtx.common;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

public class DpopenSecurityUtil {

	public static String getJingDongDigest(String plainText)
	{
		String str = DigestUtils.md5Hex(plainText);

		return str;
	}

	private static byte[] mD5Byte(String plainText, String charset)
			throws UnsupportedEncodingException
	{
		return DigestUtils.md5(plainText.getBytes(charset));
	}

	public static String base64(String plainText)
	{
		return Base64.encodeBase64String(plainText.getBytes());
	}

	public static String getCommonDigest(String plainText, String charset)
	{
		return getDigest(plainText);
	}

	public static String getTaobaoDigest(String plainText, String charset)
	{
		try
		{
			return new String(Base64.encodeBase64(mD5Byte(plainText, charset)), charset);
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public static String getCainiaoDigest(String plainText, String charset)
	{
		try
		{
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes(charset));
			return new String(Base64.encodeBase64(md.digest()), charset);
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public static String getAlibabaDigest(String plainText)
	{
		return Base64.encodeBase64String(DigestUtils.md5Hex(plainText).getBytes());
	}

//	public static String getAlibabaPACDigest(String plainText)
//	{
//		try
//		{
//			MessageDigest md = MessageDigest.getInstance("MD5");
//			md.update(plainText.getBytes("utf-8"));
//			sign = new String(Base64.encodeBase64(md.digest()), "utf-8");
//		}
//		catch (Exception e)
//		{
//			String sign;
//			throw new IllegalArgumentException(e);
//		}
//		String sign;
//		return sign;
//	}

	public static String getKingdeeDigest(String plainText)
	{
		return getDigest(plainText);
	}

	public static String getTAOBAOJZDigest(String plainText)
	{
		return getDigest(plainText);
	}

	public static String getQQSudiDigest(String plainText)
	{
		return getDigest(plainText);
	}

	public static String getStandardDigest(String plainText)
	{
		return getDigest(plainText);
	}

	public static String getDigest(String plainText)
	{
		return Base64.encodeBase64String(DigestUtils.md5Hex(plainText).getBytes());
	}

	public static String sHA1Encode(String sourceString)
	{
		String resultString = null;
		try
		{
			resultString = new String(sourceString);
			MessageDigest md = MessageDigest.getInstance("SHA1");
			byte[] bytes = md.digest(resultString.getBytes());
			StringBuffer buf = new StringBuffer(bytes.length * 2);
			for (int i = 0; i < bytes.length; i++)
			{
				if ((bytes[i] & 0xFF) < 16) {
					buf.append("0");
				}
				buf.append(Long.toString(bytes[i] & 0xFF, 16));
			}
			resultString = buf.toString();
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			resultString = "";
		}
		return resultString;
	}

	public static String getMicrocreditDigest(String plainText, String charset)
	{
		String digest = "";
		try
		{
			digest = DigestUtils.md5Hex(plainText.getBytes(charset));
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		return digest;
	}

	public static String randomString(int length)
	{
		if (length < 1) {
			return null;
		}
		String basicchars = "0123456789abcdefghijklmnopqrstuvwxy";

		Random randGen = new Random();
		char[] numbersAndLetters = basicchars.toCharArray();
		char[] randBuffer = new char[length];
		for (int i = 0; i < randBuffer.length; i++) {
			randBuffer[i] = numbersAndLetters[randGen.nextInt(basicchars.length() - 1)];
		}
		return new String(randBuffer);
	}

	public static String getMD5Str(String str)
	{
		MessageDigest messageDigest = null;
		StringBuffer md5StrBuff = new StringBuffer();
		try
		{
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes("UTF-8"));
			byte[] byteArray = messageDigest.digest();
			for (int i = 0; i < byteArray.length; i++) {
				if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
					md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
				} else {
					md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
				}
			}
		}
		catch (NoSuchAlgorithmException e)
		{
			System.out.println("NoSuchAlgorithmException caught!");
			md5StrBuff.append("");
			System.exit(-1);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			md5StrBuff.append("");
			System.exit(-1);
		}
		return md5StrBuff.toString();
	}

	public static String getVerifyData(String shippingId, String xml, String strConst)
	{
		String verify = null;
		String rdm1 = randomString(4);
		String rdm2 = randomString(4);
		String str = rdm1 + shippingId + xml + strConst + rdm2;
		String strmd5 = getMD5Str(str);
		verify = rdm1 + strmd5.substring(7, 28) + rdm2;

		return verify;
	}

	public static String md5Signature(TreeMap<String, String> params, String secret)
	{
		String result = null;

		StringBuffer orgin = getBeforeSign(params, new StringBuffer(secret));
		if (orgin == null) {
			return result;
		}
		orgin.append(secret);
		try
		{
			MessageDigest md = MessageDigest.getInstance("MD5");
			result = byte2hex(md.digest(orgin.toString().getBytes("utf-8")));
		}
		catch (Exception e)
		{
			throw new RuntimeException("TOP_API_PARAM has to MD5_Sign was Error !");
		}
		return result;
	}

	public static String md5Signature(LinkedHashMap<String, String> params, String secret)
	{
		String result = null;

		StringBuffer orgin = getBeforeSign(params, new StringBuffer(secret));
		if (orgin == null) {
			return result;
		}
		orgin.append(secret);
		try
		{
			MessageDigest md = MessageDigest.getInstance("MD5");
			result = byte2hex(md.digest(orgin.toString().getBytes("utf-8")));
		}
		catch (Exception e)
		{
			throw new RuntimeException("TOP_API_PARAM has to MD5_Sign was Error !");
		}
		return result;
	}

	private static String byte2hex(byte[] b)
	{
		StringBuffer hs = new StringBuffer();

		String stmp = "";
		for (int n = 0; n < b.length; n++)
		{
			stmp = Integer.toHexString(b[n] & 0xFF);
			if (stmp.length() == 1) {
				hs.append("0").append(stmp);
			} else {
				hs.append(stmp);
			}
		}
		return hs.toString().toUpperCase();
	}

	private static StringBuffer getBeforeSign(TreeMap<String, String> params, StringBuffer orgin)
	{
		if (params == null) {
			return null;
		}
		Map<String, String> treeMap = new TreeMap();
		treeMap.putAll(params);

		Iterator<String> iter = treeMap.keySet().iterator();
		while (iter.hasNext())
		{
			String name = (String)iter.next();
			orgin.append(name).append((String)params.get(name));
		}
		return orgin;
	}

	private static StringBuffer getBeforeSign(LinkedHashMap<String, String> params, StringBuffer orgin)
	{
		if (params == null) {
			return null;
		}
		Map<String, String> treeMap = new TreeMap();
		treeMap.putAll(params);

		Iterator<String> iter = treeMap.keySet().iterator();
		while (iter.hasNext())
		{
			String name = (String)iter.next();
			orgin.append(name).append((String)params.get(name));
		}
		return orgin;
	}

	public static String signTopRequest(String param, String secret)
			throws IOException
	{
		byte[] bytes = encryptMD5(param.getBytes("utf-8"));

		return byte2hex(bytes);
	}

	public static byte[] encryptMD5(byte[] data)
			throws IOException
	{
		byte[] bytes = null;
		try
		{
			MessageDigest md = MessageDigest.getInstance("MD5");
			bytes = md.digest(data);
		}
		catch (GeneralSecurityException gse)
		{
			throw new IOException(gse.getMessage());
		}
		return bytes;
	}

	public static String topbyte2hex(byte[] bytes)
	{
		StringBuilder sign = new StringBuilder();
		for (int i = 0; i < bytes.length; i++)
		{
			String hex = Integer.toHexString(bytes[i] & 0xFF);
			if (hex.length() == 1) {
				sign.append("0");
			}
			sign.append(hex.toUpperCase());
		}
		return sign.toString();
	}

	public static void main(String[] args)
	{
		long ts = System.currentTimeMillis();
		System.out.println(ts);

		String txt = "{\"logisticCompanyID\":\"DEPPON\",\"logisticID\":\"SD20130523036��}cba1231376620960488";

		String result = getCommonDigest(txt, "utf-8");
		System.out.println(result);
		String appkey = "xbkgdeppon20160921";
		System.out.println(getMD5Str(appkey));
	}
}
